import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getUserProfile, getUSerDetailById } from '@/api/user.js'

// 暴露仓库实例对象
export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    updateToken(state, token) {
      state.token = token
      setToken(token)
    },
    removeToken(state, token) {
      state.token = ''
      removeToken()
    },
    updateUserInfo(state, info) {
      console.log('info', info)
      state.userInfo = info
    },
    removeUserinfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    // 获取token 存储到vuex中
    async userLogin(context, loginForm) {
      const res = await login(loginForm)
      // console.log('res', res)
      context.commit('updateToken', res.data)
    },
    // 获取用户信息res.data存储到vuex中
    async getUserInfo(context) {
      try {
        // 获取用户信息
        const res = await getUserProfile()
        // console.log('getUserProfile', res)
        // 获取用户id
        const info = await getUSerDetailById(res.data.userId)
        context.commit('updateUserInfo', { ...res.data, ...info.data })
      } catch (error) {
        console.log('error getUserInfo', error)
      }
    },
    // 退出登录
    logout(context) {
      context.commit('removeToken')
      context.commit('removeUserInfo')
    }
  }
}
